<template>
  <Dialog v-model="dialogVisible" title="卡片详情" width="800px">
    <el-descriptions :column="2" border>
      <el-descriptions-item label="卡片ID">
        {{ detailData.id }}
      </el-descriptions-item>
      <el-descriptions-item label="卡号">
        {{ detailData.cardNumber }}
      </el-descriptions-item>
      <el-descriptions-item label="卡密">
        {{ detailData.cardPassword }}
      </el-descriptions-item>
      <el-descriptions-item label="SKU信息">
        {{ formatSkuInfo(detailData) }}
      </el-descriptions-item>
      <el-descriptions-item label="卡类型">
        <dict-tag :type="DICT_TYPE.CARD_TYPE" :value="detailData.type" />
      </el-descriptions-item>
      <el-descriptions-item label="卡状态">
        <dict-tag :type="DICT_TYPE.CARD_STATUS" :value="detailData.status" />
      </el-descriptions-item>
      <el-descriptions-item label="门店类型">
        <dict-tag :type="DICT_TYPE.OUTLET_TYPE" :value="detailData.outletType" />
      </el-descriptions-item>
      <el-descriptions-item label="门店">
        {{ detailData.outletName || '-' }}
      </el-descriptions-item>
      <el-descriptions-item label="激活用户">
        {{ detailData.userName || '-' }}
      </el-descriptions-item>
      <el-descriptions-item label="启用状态">
        <dict-tag :type="DICT_TYPE.COMMON_STATUS" :value="detailData.enable" />
      </el-descriptions-item>
      <el-descriptions-item label="创建时间" :span="2">
        {{ formatDate(detailData.createTime) }}
      </el-descriptions-item>
    </el-descriptions>

    <!-- 如果有属性信息，展示属性详情 -->
    <template v-if="detailData.properties && detailData.properties.length > 0">
      <el-divider content-position="left">SKU属性详情</el-divider>
      <el-table :data="detailData.properties" border style="width: 100%">
        <el-table-column label="属性名称" align="center" prop="propertyName" />
        <el-table-column label="属性值" align="center" prop="valueName" />
      </el-table>
    </template>

    <!-- 流转记录 -->
    <el-divider content-position="left">流转记录</el-divider>
    <el-table v-loading="recordLoading" :data="recordList" border style="width: 100%" max-height="400">
      <el-table-column label="操作时间" align="center" width="180">
        <template #default="scope">
          {{ formatOperationTime(scope.row.operationTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作类型" align="center" prop="operationType" width="120">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.CARD_OPERATION_TYPE" :value="scope.row.operationType" />
        </template>
      </el-table-column>
      <el-table-column label="操作人" align="center" prop="operatorName" width="120" />
      <el-table-column label="状态变更" align="center" width="200">
        <template #default="scope">
          <template v-if="scope.row.beforeStatus !== null && scope.row.afterStatus !== null">
            <dict-tag :type="DICT_TYPE.CARD_STATUS" :value="scope.row.beforeStatus" />
            <Icon icon="ep:right" class="mx-5px" />
            <dict-tag :type="DICT_TYPE.CARD_STATUS" :value="scope.row.afterStatus" />
          </template>
          <template v-else-if="scope.row.afterStatus !== null">
            <dict-tag :type="DICT_TYPE.CARD_STATUS" :value="scope.row.afterStatus" />
          </template>
          <template v-else>-</template>
        </template>
      </el-table-column>
      <el-table-column label="扩展信息" align="center" min-width="250">
        <template #default="scope">
          <div v-if="parseExtendData(scope.row)" style="text-align: left; padding: 0 10px;">
            <div v-for="(value, key) in parseExtendData(scope.row)" :key="key" style="line-height: 1.8;">
              <span style="color: #909399;">{{ key }}：</span>
              <span>{{ value }}</span>
            </div>
          </div>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" min-width="150" show-overflow-tooltip />
    </el-table>

    <template #footer>
      <el-button @click="dialogVisible = false">关 闭</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { DICT_TYPE } from '@/utils/dict'
import { formatDate } from '@/utils/formatTime'
import type { CardVO } from '@/api/dc/card'
import { CardRecordApi, type CardRecordVO } from '@/api/dc/cardRecord'
import dayjs from 'dayjs'

const dialogVisible = ref(false)
const detailData = ref<CardVO>({} as CardVO)
const recordLoading = ref(false)
const recordList = ref<CardRecordVO[]>([])

/** 格式化SKU信息 */
const formatSkuInfo = (row: CardVO) => {
  if (!row.properties || !Array.isArray(row.properties) || row.properties.length === 0) {
    return row.skuId || '-'
  }
  return row.properties.map((item) => item.valueName).join('-')
}

/** 格式化操作时间（支持时间戳和字符串） */
const formatOperationTime = (time: string | number | undefined): string => {
  if (!time) {
    return '-'
  }
  // 如果是时间戳（number类型），使用 dayjs 直接格式化
  return dayjs(time).format('YYYY-MM-DD HH:mm:ss')
}

/** 解析扩展数据，返回整个对象用于展示 */
const parseExtendData = (record: CardRecordVO): Record<string, any> | null => {
  if (!record.extendData) {
    return null
  }
  try {
    const extendData = JSON.parse(record.extendData)
    // 过滤掉空值
    return Object.keys(extendData).length > 0 ? extendData : null
  } catch (error) {
    console.error('解析extendData失败', error)
    return null
  }
}

/** 查询流转记录 */
const getRecordList = async (skuId: number, cardNumber: string) => {
  try {
    recordLoading.value = true
    const data = await CardRecordApi.getCardRecordListBySkuIdAndCardNumber(skuId, cardNumber)
    recordList.value = data
  } catch (error) {
    console.error('查询流转记录失败', error)
    recordList.value = []
  } finally {
    recordLoading.value = false
  }
}

/** 打开详情弹窗 */
const open = (data: CardVO) => {
  detailData.value = data
  dialogVisible.value = true
  // 查询流转记录
  if (data.skuId && data.cardNumber) {
    getRecordList(data.skuId, data.cardNumber)
  }
}

defineExpose({ open })
</script>

